package services

import (
	"GOPAAS/internal/app/model"
	"errors"
	"gorm.io/gorm"
	"time"
)

type CompanyService struct {
	model.ResCompany
}

func GetCompanyService(cid int64) *CompanyService {
	db = getDB()
	var Company model.ResCompany
	if cid > 0 {
		db.First(&Company, cid)
	}
	return &CompanyService{Company}
}

// AddCompany 用户名密码登陆
func AddCompany(tx *gorm.DB, CompanyName string) (company model.ResCompany, err SignupErr) {
	if tx == nil {
		tx = getDB()
	}
	res := tx.Where("name = ?", CompanyName).First(&company)
	if res.RowsAffected != 0 {
		err.Err = errors.New("公司已存在")
		return
	}
	var result *gorm.DB
	partner := model.ResPartner{Name: CompanyName, IsCompany: true, DisplayName: CompanyName}
	result = tx.Select("Name", "IsCompany", "DisplayName", "Lang", "Tz", "Active", "CreateDate", "WriteDate", "AccessToken").Create(&partner)
	err.Err = result.Error
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	company = model.ResCompany{Name: CompanyName, PartnerId: partner.Id, AccountOpeningDate: time.Now().Format("2006-01-02")}
	result = tx.Select("Name", "PartnerId", "CurrencyId", "LayoutBackground", "CreateDate", "WriteDate", "FiscalyearLastDay", "FiscalyearLastMonth", "AccountOpeningDate", "PoLead", "SecurityLead").Create(&company) // 通过数据的指针来创建
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	result = tx.Model(&partner).Updates(map[string]interface{}{"company_id": company.Id})
	if result.Error != nil {
		err.Err = result.Error
		return
	}
	return
}
